package com.at.bigdata.spark.core.rdd.operator.transform

import org.apache.spark.{SparkConf, SparkContext}

/**
 *
 * @author cdhuangchao3
 * @date 2023/3/19 9:52 PM
 */
object Spark18_RDD_aggregateByKey3 {

  def main(args: Array[String]): Unit = {
    // 环境准备
    val sparkConf = new SparkConf()
      .setMaster("local[*]")
      .setAppName("Operator")
    val sc = new SparkContext(sparkConf)

    // 分区内
    // 分区间
    // reduceByKey 分区内、分区间 计算规则是相同的
    // TODO 算子 - key - value类型
    val rdd1 = sc.makeRDD(List(
      ("a", 1), ("a", 2), ("b", 3),
      ("b", 4), ("b", 5), ("a", 6)
    ), 2)

    // aggregateByKey 最终返回的数据结果应该和初始值的类型一致
    val rdd = rdd1.aggregateByKey("")(_ + _, _ + _)
    rdd.collect().foreach(println)

    // 获取相同key的数据的平均值 =》 (a, 3), (b, 4)
    val newRDD = rdd1.aggregateByKey( (0, 0) )(
      (t, v) => {
        println(v + ": " + t._1 + " " + t._2)
        (t._1 + v, t._2 + 1)
      },
      (t1, t2) => {
        println(t1 + "-----" + t2)
        (t1._1 + t2._1, t1._2 + t2._2)
      }
    )
    println("11111111111111111111111111111")
    newRDD.collect().foreach(println)
    newRDD.map(t => {
      (t._1, t._2._1 / t._2._2)
    }).collect().foreach(println)

    println("22222222222222222222222")
    val resultRDD = newRDD.mapValues {
      case (num, cnt) => {
        num / cnt
      }
    }
    resultRDD.collect().foreach(println)
  }

}
